/*************************************************************************
	> File Name: server.c
	> Author: hzq
	> Mail: 1593409937@qq.com 
	> Created Time: Sat 04 May 2019 05:31:13 PM DST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <pthread.h>
#include <assert.h>

#include <event2/event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/event.h>

#include "log.h"
#include "net.h"
#include "prompt.h"
#include "utility.h"

int main(int argc,char *argv[])
{
    /* 1.设置地址 */
    struct sockaddr_in sin;
    memset(&sin, 0, sizeof(struct sockaddr_in));
    sin.sin_family = AF_INET;
    short port = 10086;
    if(argc > 1 && atoi(argv[1])>0)
        port = atoi(argv[1]);
    sin.sin_port = htons(port);
    printf("argc = %d,port = %d\n",argc,port);
    struct event_base *base = event_base_new();
    /* 2.启动监听并设置有新连接时的回调函数 */
    struct evconnlistener *listener 
            = evconnlistener_new_bind(base, listener_cb, base,
                                      LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE,
                                      10, (struct sockaddr*)&sin,
                                      sizeof(struct sockaddr_in));
    
    /* 3.设置日志信息 */
    int err = init_log_file();
    assert(err == 0);

    /* 4.设置提示信息 */
    pthread_t prompt_tid;
    err = pthread_create(&prompt_tid,NULL,prompt_init,&port);
    assert(err == 0);

    event_base_dispatch(base);
    evconnlistener_free(listener);
    event_base_free(base);

    return 0;
}